<template>
  <div style="width: 100%; height: 100%;">
    <div class="yy-page yy-doctor-client" v-if="!isSample">
      <div class="yy-doctor-client_item yy-doctor-client_doctor" style="display: flex; width: 100%;">
        <div class="yy-doctor-client_item-block" >
          <label><img src="../../assets/images/doctor_32.png" style="height: 100%;"/></label>
        </div>
        <div class="yy-doctor-client_item-block" style="white-space: nowrap; flex: auto;min-width: 0">
          <label style="min-width: 80px; overflow: hidden; display: inline-flex;">
            <span style="flex: auto; min-width: 30px;overflow: hidden;">{{employee?.nickName}}</span>
            <span><el-text type="danger" v-if="currentSchedule && currentSchedule.flowFlag == 0">(停)</el-text></span>
          </label>
          <label style="min-width: 100px; overflow: hidden;flex: auto; display: flex;">
            <span style="flex: 1; min-width: 0; overflow: hidden;">{{room?.name}}</span>
            <span v-if="room?.state === 0" style="color: red;">(停)</span>
          </label>
        </div>
        <div class="yy-doctor-client_item-block">
          <el-button v-if="currentSchedule && currentSchedule.flowFlag == 1" type="danger" size="large" @click.stop="onChangeStatus(0)">暂停</el-button>
          <el-button v-if="currentSchedule && currentSchedule.flowFlag == 0"  color="#009688" size="large" @click.stop="onChangeStatus(1)">开诊</el-button>
          <el-button type="primary" size="large" @click.stop="onShowScheduleSettingDialog" style="margin-left: 5px;">排班</el-button>
        </div>
      </div>
      <div class="yy-doctor-client_item yy-doctor-client_room"  style="display: flex; width: 100%;">
        <div class="yy-doctor-client_item-block">
          <label><img src="../../assets/images/queue_32.png" style="height: 100%;"/></label>
        </div>
        <div class="yy-doctor-client_item-block" style="white-space: nowrap; flex: auto;min-width: 0">
          <label style="flex: 1;">
            {{ currentSchedule?.itemName}}
            <span v-if="currentSchedule">({{currentSchedule.departName}})</span>
          </label>
        </div>
        <div class="yy-doctor-client_item-block">
          <el-button color="#009688" type="success" size="large"  @click.stop="onChangeItem">切换</el-button>
          <el-button type="primary" size="large" @click.stop="onReCall(selectQueueItem)" style="margin-left: 5px;">
            <span>重呼</span>
          </el-button>
        </div>
      </div>
      <div class="yy-doctor-client_item yy-doctor-client_patient"  style="display: flex; width: 100%;">
        <div class="yy-doctor-client_item-block">
          <label><img src="../../assets/images/patient_32.png" style="height: 100%;"/></label>
        </div>
        <div class="yy-doctor-client_item-block" style="white-space: nowrap; flex: auto;min-width: 0">
          <label style="flex: 1;">{{selectQueueItem?.patientName}} <span>{{selectQueueLabel}}</span></label>
        </div>
        <div class="yy-doctor-client_item-block" v-if="selectQueueItem">
          <el-button color="#009688" size="large" @click.stop="onRemarkQueue('complete')">完成</el-button>
          <el-button type="danger" size="large" @click.stop="onRemarkQueue('passed')" style="margin-left: 5px;">过号</el-button>
        </div>
      </div>
      <div style="display: flex; width: 100%;padding: 0 10px;margin: 5px 0;">
        <el-button style="flex:1;border-radius: 0;" @click.stop="onRefreshPatient"><span>刷新</span> </el-button>
        <el-button type="primary" @click.stop="onCallPatient"  style="flex:1;border-radius: 0;"><span>顺呼</span> </el-button>
      </div>
      <div v-if="itemDeptConfig?.showQueueSearch" style="display: flex; width: 100%;padding: 0 10px;margin: 5px 0;">
        <el-input v-model="patientSearchKey" placeholder="请输入患者名称关键字搜索"/>
      </div>
      <div class="yy-doctor-client_item yy-doctor-client_queue">
        <el-tabs v-model="currentQueueState" @tab-change="onTabChange">
          <el-tab-pane label="待叫号" name="1,4"></el-tab-pane>
          <el-tab-pane label="已叫号" name="2"></el-tab-pane>
          <el-tab-pane label="已过号" name="3"></el-tab-pane>
          <el-tab-pane label="已完成" name="5"></el-tab-pane>
        </el-tabs>
        <div class="yy-doctor-client_queue-member">
          <WidgetTable
              class="yy-flex-table_container"
              :is-loading="queueMemberTable.isLoading"
              :columns="queueMemberTable.columns"
              :data="queueMembers"
              :formats="queueMemberTable.formats"
              :paging-data="queueMemberTable.paging"
              :options="queueMemberTable.options"
          ></WidgetTable>
        </div>
      </div>
    </div>
    <div class="yy-page yy-doctor-client yy-doctor-client--sample" v-else>
      <div class="yy-doctor-client_item yy-doctor-client_doctor">
        <span><img src="../../assets/images/doctor_32.png" style="height: 100%;"/></span>
        <span style="flex: 1; min-width: 200px;padding-right: 95px;">
        <span style="flex: 1;min-width: 50px; padding-left: 5px; display: inline-flex;padding-right: 10px;">
          <span style="min-width: 0;max-width: 100%;white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
             <span style="overflow: hidden;">{{employee?.nickName}}</span>
             <span v-if="currentSchedule">-{{ currentSchedule?.itemName}}</span>
          </span>
          <span><el-text type="danger" v-if="currentSchedule && currentSchedule.flowFlag == 0">(停)</el-text></span>
        </span>
        <span class="yy-doctor-client_item-action">
          <el-button style="border-radius: 0;" type="danger" size="small" @click.stop="onRemarkQueue('passed')" >过号</el-button>
          <el-button style="border-radius: 0;" v-if="currentSchedule && currentSchedule.flowFlag == 1" type="danger" size="small" @click.stop="onChangeStatus(0)">暂停</el-button>
          <el-button style="border-radius: 0;" v-if="currentSchedule && currentSchedule.flowFlag == 0"  color="#009688" size="small" @click.stop="onChangeStatus(1)">开诊</el-button>
        </span>
      </span>
      </div>
      <div class="yy-doctor-client_item yy-doctor-client_patient">
        <span><img src="../../assets/images/patient_32.png"/></span>
        <span style="flex: 1;padding-left: 5px; white-space: nowrap; overflow: hidden;">
          {{selectQueueItem?.patientName}}
          <span v-if="selectQueueItem">{{selectQueueLabel}}</span>
        </span>
        <span class="yy-doctor-client_item-action">
            <el-button size="small" style="border-radius: 0;" color="#009688" @click.stop="onCallPatient">顺呼</el-button>
            <el-button size="small" style="border-radius: 0;" type="primary" @click.stop="onReCall(selectQueueItem)">重呼</el-button>
            <span v-if="!isSampleExpand" class="yy-doctor-client_item-action-item" @click.stop="onExpandQueue(true)"><el-icon><Expand /></el-icon></span>
            <span v-else class="yy-doctor-client_item-action-item" @click.stop="onExpandQueue(false)"><el-icon><Fold /></el-icon></span>
        </span>
      </div>
      <div class="yy-doctor-client_item yy-doctor-client_queue" v-if="isSampleExpand">
        <el-tabs v-model="currentQueueState" @tab-change="onTabChange">
          <el-tab-pane label="待叫号" name="1,4"></el-tab-pane>
          <el-tab-pane label="已叫号" name="2"></el-tab-pane>
          <el-tab-pane label="已过号" name="3"></el-tab-pane>
          <el-tab-pane label="已完成" name="5"></el-tab-pane>
        </el-tabs>
        <div class="yy-doctor-client_queue-member">
          <WidgetTable
              class="yy-flex-table_container"
              :is-loading="queueMemberTable.isLoading"
              :columns="queueMemberTable.columns"
              :data="queueMembers"
              :formats="queueMemberTable.formats"
              :paging-data="queueMemberTable.paging"
              :options="queueMemberTable.options"
          ></WidgetTable>
        </div>
      </div>
    </div>
    <SetPatientToEmployeeDialog v-if="employee?.emplId" ref="setPatientToEmployeeDialogRef" @changeSignSuccess="onChangeSignSuccess"/>
    <EmployeeScheduleSelectorDialog v-if="employee?.emplId" ref="employeeScheduleSelectorDialogRef" :empl-id="employee.emplId" :schedule-id="currentSchedule?.id" @select-schedule="onHandleSelectSchedule"/>
    <EmployeeScheduleWeekSelect v-if="employee?.emplId" ref="employeeScheduleWeekSelectRef" :empl-id="employee.emplId" @select-schedule="onSetScheduleSuccess"/>
  </div>
</template>
<script setup lang="ts">
import {computed, onBeforeMount, onBeforeUnmount, reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {QueueRoomModel} from "@/model/QueueRoomModel";
import useUserStore from "@/store/modules/user";
import ClientApi from "@/api/doctor";
import DoctorClientApi from "@/api/doctor";
import EmployeeScheduleSelectorDialog from "./EmployeeScheduleSelectorDialog.vue";
import {
  QueueItemModel,
  QueueStateEnum,
  ScheduleSignStateEnum,
  SubQueueFlagEnum,
  VisitStateEnum
} from "@/model/QueueItemModel";
import {QueueScheduleModel} from "@/model/QueueScheduleModel";
import * as Utils from "@/utils/yayi"
import WidgetTable from "@/components/widget/WidgetTable.vue";
import {ElMessage} from "element-plus";
import StorageUtils from "@/utils/StorageUtils";
import SseActionEnum from "@/enums/SseActionEnum";
import * as SysDictDataApi from '@/api/system/dict/data'
import SetPatientToEmployeeDialog from "@/views/doctor/SetPatientToEmployeeDialog.vue";
import {DeviceModel} from "@/model/DeviceModel";
import EmployeeScheduleWeekSelect from "@/views/doctor/EmployeeScheduleWeekSelect.vue";
import {DepartItemModel} from "@/model/DepartItemModel";
import  WebSocketClient from '@/utils/WebSocketClient'
import {EnvConfig} from "@/utils";


  let websocketClient = null
  const route = useRoute()
  const router = useRouter()
  const userStore = useUserStore()
  const employeeScheduleSelectorDialogRef = ref()
  const setPatientToEmployeeDialogRef = ref()
  const employeeScheduleWeekSelectRef = ref()
  const listPatientSource = ref([])
  const itemDeptConfig = ref<DepartItemModel>()

  const patientSearchKey = ref()
  const serverTime = ref()
  const device = ref<DeviceModel>()
  const room = ref<QueueRoomModel>()
  const employee = ref()
  const selectQueueItem = ref<QueueItemModel>()
  const currentSchedule = ref<QueueScheduleModel>()
  const currentQueueState = ref("1,4")

  const isSample = ref(false)
  const isSampleExpand = ref(false)

  const selectQueueLabel = computed(() => {
    if (selectQueueItem.value) {
      const queueFlag = QueueItemModel.getQueueFlag(selectQueueItem.value.subQueueFlag)
      console.log('---queue flag----', queueFlag)
      if (queueFlag && !queueFlag.isDefault) {
        return  '(' + queueFlag.nick + ' ' + selectQueueItem.value.registerNo + '号)'
      } else{
        return '(' + selectQueueItem.value.registerNo + '号)'
      }
    }
    return '';
  })

  const queueMembers = computed(() => {
    if (patientSearchKey.value && queueMemberTable.data) {
       return queueMemberTable.data.filter(p => p.patientName.includes(patientSearchKey.value))
    }
    return queueMemberTable.data
  })

  const queueMemberTable = reactive<{
    isHide?: boolean,
    isLoading: boolean,
    paging: any,
    options: any,
    columns: any[],
    data: QueueItemModel[],
    formats?: any
  }>({
    isHide: false,
    isLoading: false,
    columns: [
      {
        field: "registerNo",
        "label": "序号",
        "showable":true,
        "fixed": 'left',
        "align": 'center',
        "width": 60,
      },
      {
        "field":"subQueueFlag",
        "label":"标识",
        "showable":true,
        "align": 'center',
        "width": 120
      },
      {
        "field":"patientName",
        "label":"姓名",
        "showable":true
      },
      {
        "field":"callCount",
        "label":"次数",
        "showable":true,
        "condition": () => {
          return currentQueueState.value == '2'
        },
        "width": 45
      },
      {
        "field":"updateTime",
        "label": () => {
          return currentQueueState.value == '3' ? '过号时间' : '完成时间'
        },
        "showable":true,
        "condition": () => {
          return currentQueueState.value != '1,4' && currentQueueState.value != '2'
        },
        "width": 80
      },
      {
        "field":"action",
        "label":"操作",
        "showable":true,
        "align": 'left',
        "fixed": 'right',
        "width": 90,
        "condition": () => {
          return currentQueueState.value != '1,4' || !itemDeptConfig.value || !itemDeptConfig.value.allowCompleteAtAwait
        },
      },{
        "field":"action",
        "label":"操作",
        "showable":true,
        "align": 'left',
        "fixed": 'right',
        "width": 130,
        "condition": () => {
          return currentQueueState.value == '1,4' && itemDeptConfig.value && itemDeptConfig.value.allowCompleteAtAwait
        },
      }
    ],
    paging: {
      isPaging: false,
    },
    options: {
      isSingleSelect: false,
      highlight: false,
    },
    data: [],
    formats: {
      'subQueueFlag': {
        type: 'tag',
        typeFormat: (flag, row) => {
          return QueueItemModel.getQueueFlag(flag)?.type
        },
        labelFormat: (flag, row) => {
          // console.log('current queue data:::', flag, row)
          if (itemDeptConfig.value?.showPatientSource) {
             const source = listPatientSource.value.find(item => item.dictValue === row.patientSource)
             if (source) {
               return source.dictLabel
             }
          }
          if (row.scheduleFlag && row.scheduleFlag === 1) {
            const fromTime = row.scheduleFromTime || ''
            const toTime = row.scheduleToTime || ''
            let nickName = QueueItemModel.getQueueFlag(flag)?.nick || ''
            if (flag == SubQueueFlagEnum.YY && (fromTime || toTime)) {
              nickName += `(${fromTime} - ${toTime})`
            }
            return nickName
          }
          return QueueItemModel.getQueueFlag(flag)?.nick
        }
      },
      'patientName': {
        labelFormat: (val, row) => {
          let patientName = val
          if (row.visitState != VisitStateEnum.AWAIT  && currentQueueState.value == '1,4' ) {
            patientName = patientName + `<span style="margin-left: 5px;">【${QueueItemModel.getVisitState(row.visitState)?.label}】</span>`
          } else if (row.passedFlag == 1) {
            patientName = patientName + `<span style="margin-left: 5px;">【过】</span>`
          } else if (row.scheduleFlag && ([ScheduleSignStateEnum.AFTER, ScheduleSignStateEnum.BEFORE].includes(row.scheduleSignState)) && currentQueueState.value == '1,4') {
            patientName = patientName + `<span style="margin-left: 5px;color: #E6A23C;">【${QueueItemModel.getScheduleSignState(row.scheduleSignState)?.label}】</span>`
          }
          return patientName;
        }
      },
      'signTime': {
        labelFormat: (val) => {
          return Utils.formatDate(val, 'HH:mm:ss')
        }
      },
      'callTime': {
        labelFormat: (val) => {
          return Utils.formatDate(val, 'HH:mm:ss')
        }
      },
      'updateTime': {
        labelFormat: (val) => {
          return Utils.formatDate(val, 'HH:mm:ss')
        }
      },
      'action': {
        items: [
          {label: '呼叫', value:'call',
            condition: (queueItem) => currentQueueState.value == '1,4',
            atClick:(queueItem) => {
              onReCall(queueItem)
            }
          },
          {label: '改签', value:'call',
            condition: (queueItem) => currentQueueState.value == '1,4' && queueItem.doctorId,
            atClick:(queueItem) => {
              onSetPatientToEmployeeDialog(queueItem)
            }
          },
          {label: '完成', value:'call',
            condition: (queueItem) => currentQueueState.value == '1,4' && queueItem.doctorId && itemDeptConfig.value?.allowCompleteAtAwait,
            atClick:(queueItem) => {
              onRemarkQueue('complete', queueItem.id)
            }
          },
          {label: '重呼', value:'recall',
            condition: (queueItem) => currentQueueState.value != '1,4',
            atClick:(queueItem) => {
              onReCall(queueItem)
            }
          }
        ]
      }
    }
  })

  onBeforeMount(() => {
    const query = route.query
    websocketClient = new WebSocketClient(EnvConfig.baseApi, query.ip, onWebsocketMessage)

    employee.value = userStore
    if (employee.value?.emplId) {
      getCurrentRoom()
    }
    window.onbeforeunload = function () {
      logout()
    }
    document.body.addEventListener('mousedown', onMouseDown)
    document.body.addEventListener('mouseup', onMouseUp)
    window.addEventListener("message", function (event) {
      const data = JSON.parse(event.data)
      if (data.action === 'SET_SAMPLE_MODE') {
        isSample.value = data.data.sampleMode
        isSampleExpand.value = data.data.isExpanded
      }
    })

    SysDictDataApi.getDicts("queue_patient_source").then((res) => {
      if (res.code === 200) {
        console.log('sys patient source data:::', res.data)
        listPatientSource.value = res.data
      }
    })
  })

  onBeforeUnmount(() => {
    document.body.removeEventListener('mousedown', onMouseDown, false)
    document.body.removeEventListener('mouseup', onMouseUp, false)
  })

  const onMouseDown = (event) => {
    const element = event.target
    if (element?.tagName.toLowerCase() === 'button' || element?.getAttribute("class")?.includes('yy-doctor-client_item-action-item')) {
      return
    }
    top.postMessage({data:
          {
            button: event.button,
            clientX: event.clientX,
            clientY: event.clientY
          }, action:'SAMPLE_EVENT_MOUSEDOWN'}, '*')
  }
  const onMouseUp = (event) => {
    top.postMessage({data: {
        button: event.button,
        clientX: event.clientX,
        clientY: event.clientY
      }, action:'SAMPLE_EVENT_MOUSEUP'}, '*')
  }

  const onWebsocketMessage = (error, data) => {
    console.log("current websocket message:::", data, data && data.action === SseActionEnum.SSE_EMPLOYEE_QUEUE_REFRESH, currentQueueState.value === '1,4')
    if (data && data.action === SseActionEnum.SSE_EMPLOYEE_CALL_CHANGE) {
      if (currentQueueState.value === '1,4') {
        onRefreshPatient()
      }
    } else if (data && data.action === SseActionEnum.SSE_EMPLOYEE_QUEUE_REFRESH) {
      if (currentQueueState.value === '1,4') {
        onRefreshPatient()
      }
    }
  }

  const getCurrentRoom = () => {
    if (employee.value?.emplId) {
      ClientApi.getCurrentRoom(employee.value.emplId).then(data => {
        if (!data) {
          ElMessage.warning("当前设备还未注册到服务端，请联系管理员。")
          StorageUtils.removeUserLoginToken()
          router.push({name: 'DoctorLogin', replace: true})
          return
        }
        device.value = data.device
        room.value = data.room
        currentSchedule.value = data.schedule
        serverTime.value = data.serverTime

        if (device.value) {
          sendDeviceHeartbeat()
        }
        if (currentSchedule.value) {
          // 医生选择出诊科目，开始发送心跳包
          websocketClient.updateScheduleData(employee.value.emplId, currentSchedule.value.id, room.value.id)

          getItemConfig()
          // 第一次要查询待叫号列表和已叫号列表
          listQueueMember()
          // 查询已经叫号的患者
          ClientApi.listDoctorQueueMember(
              currentSchedule.value.departId,
              currentSchedule.value.itemId,
              employee.value.emplId,
              currentSchedule.value.categoryId,
              '2'
          ).then((members) => {
            selectQueueItem.value = members.find(item => item.state === QueueStateEnum.ALREADY_CALLED && item.visitState === VisitStateEnum.JUST)
          })
        } else {
          // 没有排班则弹窗提醒设置
          sendOpenScheduleWindowMessage()
        }
      })
    }
  }

  const getItemConfig = () => {
    DoctorClientApi.getItemDeptRelation(currentSchedule.value.departId, currentSchedule.value.itemId).then(res => {
      console.log("get current item config:::", res)
      itemDeptConfig.value = res
    })
  }
  const sendOpenScheduleWindowMessage = () => {
    onShowScheduleSettingDialog()
  }

  const sendDeviceHeartbeat = () => {
    ClientApi.sendDeviceHeartbeat(employee.value.emplId, currentSchedule.value?.id, room.value.id, device.value.code).then((res) => {
      // 连接成功后，刷新患者列表
      if (currentQueueState.value === '1,4') {
        onRefreshPatient()
      }
      setTimeout(() => {
        sendDeviceHeartbeat()
      }, 30000)
    }, () => {
      setTimeout(() => {
        sendDeviceHeartbeat()
      }, 30000)
    })
  }

  const listQueueMember = () => {
    queueMemberTable.isLoading = true
    ClientApi.listDoctorQueueMember(
        currentSchedule.value.departId,
        currentSchedule.value.itemId,
        employee.value.emplId,
        currentSchedule.value.categoryId,
        currentQueueState.value
    ).then(members => {
      queueMemberTable.data = members
      queueMemberTable.isLoading = false
      if ((!members || members.length == 0) && selectQueueItem.value) {
        // 查询已经叫号的患者
        ClientApi.listDoctorQueueMember(
            currentSchedule.value.departId,
            currentSchedule.value.itemId,
            employee.value.emplId,
            currentSchedule.value.categoryId,
            '2'
        ).then((members) => {
          selectQueueItem.value = members.find(item => item.state === QueueStateEnum.ALREADY_CALLED && item.visitState === VisitStateEnum.JUST)
        })
      }
    }, () => {
      queueMemberTable.data = []
      queueMemberTable.isLoading = false
    })
  }

  const logout = () => {
    //
  }

  const onShowScheduleSettingDialog = () => {
    // employeeScheduleSettingDialogRef.value.onShowDialog(employee.value, currentSchedule.value)
    employeeScheduleWeekSelectRef.value.onShowDialog(employee.value, currentSchedule.value, serverTime.value)
  }

  const onSetPatientToEmployeeDialog = (queueItem: QueueItemModel) => {
    setPatientToEmployeeDialogRef.value.onShowDialog(employee.value, currentSchedule.value, queueItem)
  }

  const onSetScheduleSuccess = () => {
    // 如果当前未选择计划，则自动设置当前计划
    if (!currentSchedule.value) {
      ClientApi.listDoctorSchedule(employee.value.emplId).then(data => {
        if (data?.length) {
          onHandleSelectSchedule(data[0])
        }
      })
    }
  }

  const onHandleSelectSchedule = (schedule: QueueScheduleModel) => {
    currentSchedule.value = schedule
    // 医生选择出诊科目，开始发送心跳包
    websocketClient.updateScheduleData(employee.value.emplId, currentSchedule.value.id, room.value.id)

    getItemConfig()
    ClientApi.changeCurrentSchedule(employee.value.emplId, schedule.id, room.value.id, device.value.id)
    listQueueMember()
    // 查询已经叫号的患者
    ClientApi.listDoctorQueueMember(
        schedule.departId,
        schedule.itemId,
        employee.value.emplId,
        schedule.categoryId,
        '2'
    ).then((members) => {
      selectQueueItem.value = members.find(item => item.state === QueueStateEnum.ALREADY_CALLED && item.visitState === VisitStateEnum.JUST)
    })
  }

  const onChangeSignSuccess = () => {
    if (currentQueueState.value === '1,4') {
      onRefreshPatient()
    }
  }

  const onTabChange = () => {
    if (employee.value.emplId && currentSchedule.value) {
      listQueueMember()
    }
  }
  const onChangeItem = () => {
    if (employee.value.emplId) {
      employeeScheduleSelectorDialogRef.value.onShowDialog()
    } else {
      ElMessage.warning({
        message: '未关联员工，无法执行该操作',
        showClose: true
      })
    }
  }

  const onChangeStatus = (status) => {
    DoctorClientApi.callQueueStatu(employee.value.emplId, status).then(res => {
      currentSchedule.value.flowFlag = status
    })
  }

  const onRefreshPatient = () => {
    if (employee.value?.emplId && currentSchedule.value) {
      listQueueMember()
    }
  }

  // 从队列中按顺序呼叫
  const onCallPatient = () => {
    if (currentSchedule.value.flowFlag === 0) {
      ElMessage.warning({
        message: '您当前处于停诊状态，无法执行该操作',
        showClose: true
      })
      return
    }
    if (employee.value.emplId) {
      ClientApi.callQueueMember(currentSchedule.value.departId,  currentSchedule.value.itemId, employee.value.emplId, currentSchedule.value.categoryId, room.value.id).then((data) => {
        if(data) {
          selectQueueItem.value = data
          // 呼叫完成后，重新请求列表，为了保证预约时间段没到的患者能及时显示出来
          onRefreshPatient()
        }
      })
    } else {
      ElMessage.warning({
        message: '未关联员工，无法执行该操作',
        showClose: true
      })
    }
  }

  // 呼叫队列中指定的患者
  const onReCall = (queueItem: QueueItemModel) => {
    if (currentSchedule.value.flowFlag === 0) {
      ElMessage.warning({
        message: '您当前处于停诊状态，无法执行该操作',
        showClose: true
      })
      return
    }
    ClientApi.callQueueById(currentSchedule.value.departId, currentSchedule.value.itemId,employee.value.emplId, currentSchedule.value.categoryId, queueItem.id, room.value.id).then((data) => {
      selectQueueItem.value = data
      // 已叫号列表，更新数据
      if (currentQueueState.value == '2') {
        const index = queueMemberTable.data.findIndex(item => item.id === data.id)
        if (index >= 0) {
          queueMemberTable.data.splice(index, 1, data)
        }
      } else {
        // 待叫号列表移除当前叫号记录
        const index = queueMemberTable.data.findIndex(item => item.id === data.id)
        if (index >= 0) {
          queueMemberTable.data.splice(index, 1)
        }
      }
    })
  }

  const onRemarkQueue = (remark: string, queueItemId: string = null) => {
    const selectQueueItemId = queueItemId ? queueItemId : selectQueueItem.value.id
    if (remark === 'complete') {
      ClientApi.completeQueueById(currentSchedule.value.departId, employee.value.emplId, currentSchedule.value.itemId, currentSchedule.value.categoryId, selectQueueItemId).then(() => {
        if (currentQueueState.value == '2') {
          const index = queueMemberTable.data.findIndex(item => item.id === selectQueueItem.value.id)
          if (index >= 0) {
            queueMemberTable.data.splice(index, 1)
          }
        }
        if (!queueItemId) {
          selectQueueItem.value = null
        } else {
          const index = queueMemberTable.data.findIndex(item => item.id === queueItemId)
          if (index >= 0) {
            queueMemberTable.data.splice(index, 1)
          }
        }
      })
    } else {
      ClientApi.passQueueById(currentSchedule.value.departId, employee.value.emplId, currentSchedule.value.itemId, currentSchedule.value.categoryId, selectQueueItemId).then(() => {
        if (currentQueueState.value == '2') {
          const index = queueMemberTable.data.findIndex(item => item.id === selectQueueItem.value.id)
          if (index >= 0) {
            queueMemberTable.data.splice(index, 1)
          }
        }
        selectQueueItem.value = null
      })
    }
  }
  const onExpandQueue = (isExpand: boolean) => {
    isSampleExpand.value = !!isExpand
    top.postMessage({data: isExpand, action:'SAMPLE_EXPAND_QUEUE'}, '*')
  }
</script>
<style scoped lang="scss">
:deep(.el-button+.el-button) {
  margin-left: 6px;
}
label {
  font-weight: normal;
}
.yy-doctor-client {
  padding: 37px 0 5px 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  user-select: none;
  overflow-y: hidden;
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }
  &_item:not(:first-child) {
    border-top: 1px solid #f1f1f1;
  }
  &--sample {
    padding-top: 0px;
  }
  &--sample &_item {
    height: 35px;
    display: flex;
    & > span {
      display: inline-flex;
      align-items: center;
      height: 100%;
    }
    &-action {
      & > span {
        display: inline-flex;
        margin-left: 10px;
        padding: 4px;
        cursor: pointer;
        &:hover {
          background: #ddd;
        }
      }
    }
  }
  &_item {
    height: 50px;
    &-block {
      display: inline-flex;
      margin-left: 5px;
      & > label {
        height: 40px;
        padding: 3px;
        background: #FBFBFB;
        border: 1px solid #e6e6e6;
        display: inline-flex;
        align-items: center;
        justify-content: center;
      }
      & > button {
        border-radius: 0;
      }
    }
  }
  &_doctor, &_room, &_patient {
    display: flex;
    flex-direction: row;
    padding: 3px 8px 3px 3px;
  }
  &_queue {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
  }
  &_queue-member{
    flex:1;
    min-height: 0;
  }
}
</style>
